package com.yufu.baidu.ocr;

import android.content.Intent;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import com.yufu.baidu.ocr.ui.camera.CameraActivity;
import com.yufu.baidu.ocr.ui.camera.CameraNativeHelper;
import com.yufu.baidu.ocr.ui.camera.CameraView;

import org.json.JSONException;

import java.io.File;
import java.util.Objects;

public class IdCard {
  private final AppCompatActivity activity;
  private final PluginCall pluginCall;
  private Boolean isNativeEnable = false;

  public IdCard(AppCompatActivity activity, PluginCall call) {
    this.activity = activity;
    this.pluginCall = call;
  }

  public Intent getIntent() {
    String type = pluginCall.getString("type", "front");
    isNativeEnable = pluginCall.getBoolean("scan", false);
    String contentType = Objects.equals(type, "front") ? CameraActivity.CONTENT_TYPE_ID_CARD_FRONT : CameraActivity.CONTENT_TYPE_ID_CARD_BACK;
    Intent intent = new Intent(activity, CameraActivity.class);
    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.getSaveFile(activity.getApplication()).getAbsolutePath());
    if (isNativeEnable) {
      initNative();
      intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE, true);
      intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true);
    }
    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, contentType);
    return intent;
  }

  public void recIDCard(String idCardSide, String filePath) {
    IDCardParams param = new IDCardParams();
    param.setImageFile(new File(filePath));
    // 设置身份证正反面
    param.setIdCardSide(idCardSide);
    // 设置方向检测
    param.setDetectDirection(true);
    // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
    param.setImageQuality(10);

    OCR.getInstance(activity).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
      @Override
      public void onResult(IDCardResult result) {
        if (result != null) {
          IDCardResultJSObject data = new IDCardResultJSObject(result);
          pluginCall.resolve(data.getJSObject());
        } else {
          pluginCall.reject("识别数据为空");
        }
      }

      @Override
      public void onError(OCRError error) {
        pluginCall.reject(error.getMessage());
      }
    });
  }

  /**
   * 初始化本地质量控制模型
   */
  private void initNative() {
    CameraNativeHelper.init(activity, OCR.getInstance(activity).getLicense(),
      new CameraNativeHelper.CameraNativeInitCallback() {
        @Override
        public void onError(int errorCode, Throwable e) {
          String msg;
          switch (errorCode) {
            case CameraView.NATIVE_SOLOAD_FAIL:
              msg = "加载so失败，请确保apk中存在ui部分的so";
              break;
            case CameraView.NATIVE_AUTH_FAIL:
              msg = "授权本地质量控制token获取失败";
              break;
            case CameraView.NATIVE_INIT_FAIL:
              msg = "本地质量控制";
              break;
            default:
              msg = String.valueOf(errorCode);
          }
          BaiduOcr.log("本地质量控制初始化错误，错误原因： " + msg);
        }
      });
  }

  // 释放本地质量控制模型
  public void release() {
    if (isNativeEnable) {
      CameraNativeHelper.release();
    }
  }
}
